<template>
  <div class="details">
    <el-dialog
      :title="getCommMeterListMsg.title"
      :visible.sync="getCommMeterListMsg.dialog"
      width="85%"
      :close-on-click-modal="false"
      append-to-body
      class="allMeter"
    >
      <div align="center" class="query">
        <!-- 用户房号查询 -->
        <el-select v-model="value" filterable @change="getAddr" placeholder="请先选择小区楼栋/组！">
          <el-option
            v-for="item in blockList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select v-model="userAddr" v-if="value != null" filterable placeholder="请选择用户地址(选填)！">
          <el-option v-for="(item,i) in address" :key="i" :label="item" :value="item"></el-option>
        </el-select>
        <el-button type="warning" @click="getCommMeterMsgByUserAddr(userAddr, page, rows)" plain>查询</el-button>
        
        <!-- 用户名查询 -->
        <el-input class="input" v-model="userName" placeholder="请输入用户姓名！" @keyup.enter.native="getCommMeterMsgByUserName(userName)" clearable />
        <el-button
          class="button"
          type="primary"
          @click="getCommMeterMsgByUserName(userName)"
          plain
        >查询</el-button>

        <!-- 表编号查询 -->
        <el-input class="input" v-model="deviceNo" placeholder="请输入表编号！" @keyup.enter.native="getCommMeterMsgByDeviceNo(deviceNo)" clearable />
        <el-button
          class="button"
          type="success"
          @click="getCommMeterMsgByDeviceNo(deviceNo)"
          plain
        >查询</el-button>
      </div>

      <!-- 数据显示 -->
      <el-table
        :data="handleCommMeterList"
        header-cell-class-name="tableRow"
        cell-class-name="tableRow"
        v-loading="commMeterLoading"
        :stripe="true"
      >
        <!-- <el-table-column type="selection"></el-table-column> -->
        <el-table-column type="index" label="序号" min-width="40" fixed></el-table-column>
        <el-table-column prop="deviceNo" label="表编号" min-width="115">
          <template slot-scope="scope">
            <el-button
              @click="getDeviceDetailInfo(scope.row)"
              type="text"
              size="small"
            >{{scope.row.deviceNo}}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="用户名" min-width="60">
          <template slot-scope="scope">
            {{scope.row.userName}}
            <!-- <el-button
              @click="getUserDetailInfo(scope.row)"
              type="text"
              size="small"
            >{{scope.row.userName}}</el-button> -->
          </template>
        </el-table-column>
        <el-table-column prop="blockName" label="楼栋/组" min-width="80"></el-table-column>
        <el-table-column prop="userAddr" label="地址" min-width="80"></el-table-column>
        <el-table-column prop="readValue" label="当前读数" min-width="80"></el-table-column>
        <el-table-column prop="readTime" label="抄表时间" min-width="140"></el-table-column>
        <!-- <el-table-column prop="deviceType" label="表类型" min-width="80"></el-table-column> -->
        <el-table-column prop="userType" label="用水类型" min-width="80">
          <template slot-scope="scope">
            <div style="margin: 8px 0">
              <!-- <el-tag size="small" v-if="scope.row.userType === 0">居民用水</el-tag>
              <el-tag size="small" v-if="scope.row.userType === 1">商业用水</el-tag>
              <el-tag size="small" v-if="scope.row.userType === 2">工业用水</el-tag>
              <el-tag size="small" v-if="scope.row.userType === 3">特种行业用水</el-tag> -->
              <el-tag size="small" v-if="scope.row.userType === 1">居民用水</el-tag>
              <el-tag size="small" v-if="scope.row.userType === 2">工业用水</el-tag>
              <el-tag size="small" v-if="scope.row.userType === 3">行政事业单位用水</el-tag>
              <el-tag size="small" v-if="scope.row.userType === 4">商业用水</el-tag>
              <el-tag size="small" v-if="scope.row.userType === 5">特种行业用水</el-tag>
              <!-- <el-tag size="small" v-if="scope.row.userType === 6">其它用水</el-tag> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="表状态" min-width="70">
          <template slot-scope="scope">
            <div style="margin: 8px 0">
              <el-tag type="success" size="small" v-if="scope.row.state === 0">正常</el-tag>
              <el-tag type="danger" size="small" v-if="scope.row.state === 1">负值</el-tag>
              <el-tag type="warning" size="small" v-if="scope.row.state === 2">无数据</el-tag>
              <el-tag type="danger" size="small" v-if="scope.row.state === 3">水量超大</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="valve" label="阀门" min-width="75">
          <template slot-scope="scope">
            <div style="margin: 8px 0">
              <el-tag type="danger" size="small" v-if="scope.row.valve === 0">关阀</el-tag>
              <el-tag type="info" size="small" v-if="scope.row.valve === 1">无阀/不定</el-tag>
              <el-tag type="success" size="small" v-if="scope.row.valve === 2">开阀</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="rssi" label="信号强度" min-width="75"></el-table-column>
        <el-table-column prop="batteryVoltage" label="电量(mV)" min-width="80"></el-table-column>
        <el-table-column prop="imei" label="IMEI" min-width="120"></el-table-column>
        <el-table-column label="操作" min-width="80">
          <template slot-scope="scope">
            <el-dropdown>
              <el-button type="primary" plain>
                <i class="el-icon-more"></i>
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button
                    type="text"
                    style="font-size: 1.6em; color: #67c23a"
                    :disabled="scope.row.valve === 2 || scope.row.valve === 1"
                    icon="el-icon-switch-button"
                    @click="controlValve(scope.row, 2, 2)"
                  >开阀</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    type="text"
                    style="font-size: 1.6em; color: #f56c6c"
                    :disabled="scope.row.valve === 0 || scope.row.valve === 1"
                    icon="el-icon-switch-button"
                    @click="controlValve(scope.row, 2, 0)"
                  >关阀</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    type="text"
                    style="font-size: 1.6em; color: #ec971f"
                    icon="el-icon-check"
                    @click="getData(scope.row,0)"
                  >获取</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    type="text"
                    style="font-size: 1.6em"
                    icon="el-icon-refresh"
                    @click="updateData(scope.row, 0, 1)"
                  >刷新</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button
                    type="text"
                    style="font-size: 1.6em; color: red"
                    icon="el-icon-delete"
                    @click="deleteData(scope.row, 1)"
                  >删除</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin-top: 20px; text-align: center"
        @size-change="sChange"
        @current-change="pChange"
        hide-on-single-page
        :current-page="page"
        :page-sizes="[10, 15, 20, 25]"
        :page-size="rows"
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        v-if="pagination"
      ></el-pagination>

      <!-- 查询结果分页 -->
      <el-pagination
        style="margin-top: 20px; text-align: center"
        @size-change="sChange2"
        @current-change="pChange2"
        hide-on-single-page
        :current-page="page"
        :page-sizes="[10, 15, 20, 25]"
        :page-size="rows"
        background
        layout="total, prev, pager, next, jumper"
        :total="total"
        v-if="!pagination"
      ></el-pagination>
    </el-dialog>
  </div>
</template>

<script>
import bus from "./bus";
import {
  getCommMeterList,
  getFailedCommMeterList,
  getCommMeterByUserName,
  getCommMeterByUserAddr,
  getCommMeterByDeviceNo,
  controlNewDevice,
  updateNewDevice,
  deleteNewDevice,
  getDeArea, // 根据 blockId 获取楼栋下的 用户房号
  getUserByArea
} from "../../../../api/api";
import { mapState, mapGetters } from "vuex";
import moment from "moment";

export default {
  data() {
    return {
      page: 1, // 分页，页码
      rows: 15, // 分页，每页数据条数
      pagination: 1,
      commMeterList: [], // 显示表数据
      total: 0, // 数据总条数
      commMeterLoading: false, // 查看表时的加载动画
      communityId: [],
      userName: null, // 根据用户姓名查询
      userAddr: null, // 根据用户地址查询
      deviceNo: null, // 根据表编号查询
      blockId: null,
      value: null,
      blockList: [],
      address: []
    };
  },
  computed: {
    // 用 mapGetters 来获取 meterReadingManagement.js里面的 getters
    ...mapGetters("meterReadingManagement", {
      getCommMeterListMsg: "showCommMeterList"
    }),

    /**
     * 对获取的表数据的显示格式进行修改
     */
    handleCommMeterList: function() {
      //时间格式未处理
      if (this.commMeterList.length == 0) return;
      this.commMeterList.forEach(function(item) {
        switch (item.deviceType) {
          case 1:
            item.deviceType = "集抄器";
            break;
          case 2:
            item.deviceType = "NB-电信";
            break;
          case 3:
            item.deviceType = "NB-移动";
            break;
          case 4:
            item.deviceType = "Lora-wan";
            break;
          case 5:
            item.deviceType = "IC卡";
            break;
          case 6:
            item.deviceType = "机械表";
            break;
        }
        item.readTime = moment(item.readTime).format("YYYY-MM-DD HH:mm:ss");
      });
      return this.commMeterList;
    }
  },
  methods: {
    /**
     * 获取小区楼栋
     */
    getAreaInfo() {
      let that = this;
      that.commMeterLoading = true;
      let msg = {
        communityId: that.getCommMeterListMsg.communityId,
        enprNo: that.getCommMeterListMsg.enprNo,
        page: this.page,
        rows: this.rows
      };
      getCommMeterList(msg)
        .then(function(res) {
          if (res.data.code === "200") {
            for (let i = 0; i < res.data.blockList.length; i++) {
              that.blockList.push({ value: "", label: "" });
              that.blockList[i].value = res.data.blockList[i].blockId;
              that.blockList[i].label = res.data.blockList[i].blockName;
            }
          } else {
            that.Error("获取小区楼栋信息失败！");
          }
        })
        .catch(function(err) {
          // that.Error(err);
          that.commMeterLoading = false;
        });
    },
    /**
     * 根据blockId获取具体住址
     */
    getAddr(blockId) {
      let that = this;
      that.blockId = blockId;
      let msg = { blockId: blockId };
      getDeArea(msg)
        .then(function(res) {
          if (res.data.code === "200") {
            that.address = res.data.data.sort();
          } else {
            that.Error("获取该小区楼栋用户地址失败！");
          }
        })
        .catch(function(err) {
          // that.Error(err);
        });
    },

    /**
     * 获取小区的所有表
     */
    GetCommMeterList(page, rows) {
      let that = this;
      that.commMeterLoading = true;
      let msg = {
        communityId: that.getCommMeterListMsg.communityId,
        enprNo: that.getCommMeterListMsg.enprNo,
        page: page,
        rows: rows
      };
      getCommMeterList(msg)
        .then(function(res) {
          if (res.data.code === "200") {
            that.commMeterList = res.data.data.content;
            that.commMeterList.forEach(function(item) {
              for (var i = 0; i < res.data.blockList.length; i++) {
                if (item.blockId == res.data.blockList[i].blockId) {
                  item.blockName = res.data.blockList[i].blockName;
                }
              }
            });
            that.total = res.data.total;
            that.commMeterLoading = false;
          } else {
            that.Error("获取表信息失败！");
          }
          return res;
        })
        .catch(function(err) {
          // that.Error(err);
        });
    },
    getCommMeterList() {
      let page = this.page;
      let rows = this.rows;
      this.GetCommMeterList(page, rows);
    },

    /**
     * 获取失败表
     */
    GetFailedCommMeterList(page, rows) {
      let that = this;
      that.commMeterLoading = true;
      let msg = {
        communityId: that.getCommMeterListMsg.communityId,
        enprNo: that.getCommMeterListMsg.enprNo,
        page: page,
        rows: rows
      };
      getFailedCommMeterList(msg)
        .then(function(res) {
          if (res.data.code === "200") {
            that.commMeterList = res.data.info.content;
            that.total = res.data.total;
            that.commMeterLoading = false;
          } else {
            that.Error("获取表信息失败！");
          }
        })
        .catch(function(err) {
          // that.Error(err);
        });
    },
    getFailedCommMeterList() {
      let page = this.page;
      let rows = this.rows;
      this.GetFailedCommMeterList(page, rows);
    },

    /**
     *  查询
     */
    // 根据用户姓名查询
    getCommMeterMsgByUserName(userName) {
      let that = this;
      that.commMeterLoading = true;
      this.isPagination = false;
      let msg = {
        enprNo: 'esss',
        userName: userName
      };
      that.commMeterList = [];
      getCommMeterByUserName(msg)
        .then(function(res) {
          if (res.data.code === "200" && res.data.info[0]) {
            that.commMeterList = res.data.info[0].deviceDetailList;
            that.total = that.commMeterList.length;
            that.commMeterLoading = false;
          } else {
            that.Info("请输入正确的用户名！");
            that.commMeterLoading = false;
          }
        })
        .catch(function(err) {
          that.Error("根据用户姓名查询表信息失败！");
        });
    },

    // 根据表编号查询
    getCommMeterMsgByDeviceNo(deviceNo) {
      let that = this;
      that.commMeterLoading = true;
      this.isPagination = false;
      let msg = {
        enprNo: 'esss',
        deviceNo: deviceNo
      };
      that.commMeterList = [];
      getCommMeterByDeviceNo(msg)
        .then(function(res) {
          if (res.data.code === "200") {
            if (res.data.info.deviceDetailList.length == 1) {
              that.commMeterList = res.data.info.deviceDetailList;
            } else if (res.data.info.deviceDetailList.length > 1) {
              // 可能出现一户有多个水表的情况
              for (var i = 0; i < res.data.info.deviceDetailList.length; i++) {
                if (
                  res.data.info.deviceDetailList[i].deviceNo == that.deviceNo
                ) {
                  that.commMeterList.push(res.data.info.deviceDetailList[i]);
                } else continue;
              }
            }
            that.total = that.commMeterList.length;
            that.commMeterLoading = false;
            // that.commMeterList = res.data.info.deviceDetailList;
          } else {
            that.Info("请输入正确的表编号！");
            that.commMeterLoading = false;
          }
        })
        .catch(function(err) {
          // that.Error(err);
        });
    },

    // 根据blockId和具体住址查询
    GetCommMeterMsgByUserAddr(userAddr, page, rows) {
      let that = this;
      that.commMeterLoading = true;
      // this.isPagination = false;
      that.commMeterList = [];
      let msg = {
        blockId: that.blockId,
        userAddr: userAddr,
        page: page,
        rows: rows
      };
      getCommMeterByUserAddr(msg)
        .then(function(res) {
          if (res.data.code === "200") {
            if (userAddr != null) {
              res.data.info[0].deviceDetailList;
              that.commMeterList = res.data.info[0].deviceDetailList;
            } else {
              // that.commMeterList = res.data.info;
              res.data.info.forEach(item => {
                that.commMeterList.push(item.deviceDetailList[0]);
              });
              that.total = res.data.size;
            }
            that.commMeterLoading = false;
          } else {
            that.Info("请选择正确的用户房号！");
            that.commMeterLoading = false;
          }
          that.value = null;
          that.userAddr = null;
        })
        .catch(function(err) {
          that.Error("根据用户地址查询表信息失败！");
          that.commMeterLoading = false;
        });
    },
    getCommMeterMsgByUserAddr(userAddr) {
      let page = this.page;
      let rows = this.rows;
      this.pagination = 0;
      this.GetCommMeterMsgByUserAddr(userAddr, page, rows);
    },

    /* 控制 */
    getData(row, commandNo) {
      let that = this;
      let msg = {
        macAddr: row.macAddr,
        command: commandNo,
        value01: 0
      };
      that
        .$confirm("此操作将发送获取数据指令，确定吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info"
        })
        .then(() => {
          controlNewDevice(msg)
            .then(res => {
              if (res.data.code == 200) {
                that.Success("获取数据指令发送成功！");
                return;
              } else {
                that.Error("获取数据指令失败！");
              }
            })
            .catch(err => {
              // taht.Error(err);
            });
        });
    },

    // 开关阀
    controlValve(row, commandNo, onOff) {
      let that = this;
      let msg = {
        macAddr: row.macAddr,
        command: commandNo,
        value01: onOff
      };
      that.onOrOff = onOff ? "开阀" : "关阀";
      that
        .$confirm("此操作将发送" + that.onOrOff + "指令,确定吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info"
        })
        .then(() => {
          controlNewDevice(msg)
            .then(res => {
              if (res.data.code == 200) {
                that.Success(that.onOrOff + "指令发送成功！");
              } else {
                that.Error(that.onOrOff + "指令发送失败！");
              }
            })
            .catch(() => {
              // taht.Error(err);
            });
        });
    },

    // 刷新数据
    updateData(row, check, flag) {
      let that = this;
      let msg = {
        check: check,
        flag: flag,
        macAddr: row.macAddr
      };
      that.refreshWhich = flag === 0 ? "所有" : "当前";
      that.refreshWhat = flag === 2 ? "阀门状态" : "全部数据";
      that
        .$confirm(
          "此操作将刷新" +
            that.refreshWhich +
            "水表" +
            that.refreshWhat +
            "，确定吗？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "info"
          }
        )
        .then(() => {
          updateNewDevice(msg)
            .then(res => {
              if (res.data.code == 200) {
                that.Success("刷新数据指令发送成功！");
              } else {
                that.Error("刷新数据指令发送失败！");
              }
            })
            .catch(err => {
              // that.Error(err);
            });
        });
    },

    // 删除数据
    deleteData(row, flag) {
      let that = this;
      let msg = {
        enprNo: 'esss',
        flag: flag,
        imei: row ? row.imei : row
      };
      that.deleteWhich = flag === 0 ? "所有" : "当前";
      that
        .$confirm(
          "此操作将删除" + that.deleteWhich + "水表，确定吗？",
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
        .then(() => {
          deleteNewDevice(msg)
            .then(res => {
              if (res.data.code == 200) {
                if (that.getCommMeterListMsg.type === 0) {
                  that.getCommMeterList();
                } else {
                  that.getFailedCommMeterList();
                }
                that.Success("删除成功！");
              } else {
                that.Error("删除失败！");
              }
            })
            .catch(error => {
              // that.Error(error);
            });
        });
    },

    // 获取指定用户信息，给 userDialog 传递信息
    getUserDetailInfo(row) {
      let getUserDetailInfoMsg = { userId: row.userId };
      bus.$emit("getUserDetailInfo", getUserDetailInfoMsg);
    },

    // 获取指定表的信息，给deviceDialog传递信息
    getDeviceDetailInfo(row, flag) {
      let getDeviceDetailInfoMsg = {
        deviceNo: row.deviceNo,
        flag: 0
      };
      bus.$emit("getDeviceDetailInfo", getDeviceDetailInfoMsg);
    },

    // 分页
    pChange(val) {
      let rows = this.rows;
      if (this.getCommMeterListMsg.type === 0) {
        this.GetCommMeterList(val, rows);
      } else if (this.getCommMeterListMsg.type === 1) {
        this.GetFailedCommMeterList(val, rows);
      }
    },
    sChange(val) {
      let page = this.page;
        // this.GetCommMeterMsgByUserAddr(userAddr, page, val);
      if (this.getCommMeterListMsg.type === 0) {
        this.GetCommMeterList(page, val);
      } else if (this.getCommMeterListMsg.type === 1) {
        this.GetFailedCommMeterList(page, val);
      }
    },
    pChange2(val) {
      let rows = this.rows;
      let userAddr = this.userAddr;
      this.GetCommMeterMsgByUserAddr(userAddr, val, rows);
    },
    sChange2(val) {
      let page = this.page;
      let userAddr = this.userAddr;
      this.GetCommMeterMsgByUserAddr(userAddr, page, val);
    },
    

    /**
     * 提示框
     */
    Success(str) {
      this.$alert(String(str), "提示", {
        confirmButtonText: "确定",
        type: "success"
      });
    },
    Info(str) {
      this.$alert(String(str), "提示", {
        confirmButtonText: "确定",
        type: "info"
      });
    },
    Warning(str) {
      this.$alert(String(str), "提示", {
        confirmButtonText: "确定",
        type: "warning"
      });
    },
    Error(str) {
      this.$alert(String(str), "提示", {
        confirmButtonText: "确定",
        type: "error"
      });
    }
  },

  created() {
    if (this.getCommMeterListMsg.type === 0) {
      this.getCommMeterList();
    } else {
      this.getFailedCommMeterList();
    }
  },

  mounted() {
    let that = this;
    that.getAreaInfo();
  }
};
</script>

<style scoped>
/* .tableRow {
  text-align: center !important;
} */
/* 输入框样式 */
.input {
  display: inline-block;
  min-width: 100px;
  max-width: 150px;
  margin: 10px 0;
}
/* 控制查询框中间的间距 */
.button {
  margin-right: 15px;
}
.allMeter {
  top: -10%;
}
/* 对话框关闭按钮 */
.allMeter >>> .el-dialog__headerbtn {
  font-size: 1.3em;
  color: #fff;
  background: red;
  padding: .2em;
  border-radius: 3px;
}
</style>